//
//  JHPlayViewController.m
//  Liberty Voice
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ClearLove. All rights reserved.
//

#import "JHPlayViewController.h"
#import "CustomTabBarController.h"
#import "JHAudio.h"
#import "JHPlayBackViewController.h"



@interface JHPlayViewController () 

@property (nonatomic, retain)UILabel *titelLabel;
@property (nonatomic, assign)NSInteger selectedIndex;

@end


@implementation JHPlayViewController



+ (JHPlayViewController *)sharePlayerController
{
    static JHPlayViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[JHPlayViewController alloc] init];
        
       
    });
    return playerVC;

}

- (void)dealloc
{
//    [_processSlider release];
//    [_roundView release];
//    [_buttonpause release];
//    [_arr release];
//    [_player release];
//    [_timeLabel release];
//    [_timer release];
//    [_buttonplay release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"localBG"]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//     Do any additional setup after loading the view, typically from a nib.
    if (!self.arr) {
        self.arr = [[NSMutableArray alloc]init];
    }
    self.musicManager = [JHMusicDataManager shareInstance];
    [_musicManager openDB];
    NSMutableArray *a3 = [_musicManager selectInfo];
    self.arr = a3;
    [self yemianbuju];
    
}

- (void)setStr:(JHgequ *)str
{
    if (_str) {
        if (str != _str) {
            [_str release];
            _str = [str retain];
        }
    }else{
        _str = [[JHgequ alloc]init];
        _str = [str retain];
        NSLog(@"ELSE");
    }
    if (!_arr) {
        self.arr = [[NSMutableArray alloc]init];
    }
   
    
    /**
     *  数据库
     */

    [_musicManager createTable];
    JHgequ *aaaa = [[JHgequ alloc] init];
    NSLog(@"%@",_str.title);
    aaaa.title = _str.title;
    aaaa.playPath32 = _str.playPath32;
    [_musicManager insertInfoWithlanou:aaaa];
    
    NSMutableArray *a = [_musicManager selectInfo];
    for (JHgequ *aaa in a) {
        NSLog(@"----------%@", aaaa.title);
        NSLog(@"++++++++++%@", aaa.title);
        if ([aaa.title isEqualToString:aaaa.title]) {
            [_musicManager deleteInfoWithNum:aaa.title];
            [_musicManager insertInfoWithlanou:aaaa];
            
        }
    }
    self.arr = a;
    NSLog(@"%@",_arr);
}

- (void)yemianbuju
{

        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"localBG"]];
    
        self.roundView = [[JingRoundView alloc] initWithFrame:CGRectMake(15, self.view.frame.size.height / 5.5, self.view.frame.size.width - 30, self.view.frame.size.width - 29)];
        self.roundView.delegate = self;
        self.roundView.roundImage = [UIImage imageNamed:@"efb02906bc335718a37920e3a59d8122"];
        self.roundView.rotationDuration = 10.0;
        self.roundView.isPlay = NO;
        [self.view addSubview:_roundView];
        [_roundView release];


    
    UIView *bview1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 65, 65)];
    bview1.center = _roundView.center;
    bview1.alpha = 0.9;
    bview1.tag = 1111;
    [self.view addSubview:bview1];
    [bview1 release];
    
    UIView *bview2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 65, 65)];
    bview2.center = _roundView.center;
    bview2.tag = 2222;
    bview2.alpha = 0.9;
    [self.view addSubview:bview2];
    [bview2 release];
    
    

    UIButton *buttonBack = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 25, self.view.frame.size.height / 1.45, 40, 40)];
    //    buttonBack.backgroundColor = [UIColor blueColor];

    [self.view addSubview:buttonBack];
    [buttonBack setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-2"] forState:UIControlStateNormal];
    [buttonBack addTarget:self action:@selector(fanhui) forControlEvents:UIControlEventTouchUpInside];
    [buttonBack release];
    
    UIButton *buttonjilu = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 1.15, self.view.frame.size.height / 1.43, 31, 31)];
    //    buttonBack.backgroundColor = [UIColor blueColor];
    [self.view addSubview:buttonjilu];
    [buttonjilu setBackgroundImage:[UIImage imageNamed:@"iconfont-jilu"] forState:UIControlStateNormal];
    [buttonjilu addTarget:self action:@selector(jilu) forControlEvents:UIControlEventTouchUpInside];
    [buttonjilu release];

    
    
    
    self.processSlider = [[UISlider alloc] initWithFrame:CGRectMake(5 , self.view.frame.size.height / 1.18, self.view.frame.size.width - 10, self.view.frame.size.height / 30)];
    [self.view addSubview:_processSlider];
    [self.processSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateNormal];
    [_processSlider addTarget:self action:@selector(seekSlider:) forControlEvents:UIControlEventTouchUpInside];
    [_processSlider release];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height / 1.25, self.view.frame.size.width - 30, self.view.frame.size.height / 15)];
    _timeLabel.textAlignment = 2;
    [self.view addSubview:_timeLabel];
    [_timeLabel setTextColor:[UIColor lightTextColor]];
    [_timeLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:20]];
    //    _timeLabel.backgroundColor = [UIColor cyanColor];
    [_timeLabel release];
    
    
    
    self.titelLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height / 18, self.view.frame.size.width - 20, self.view.frame.size.height / 10)];
    [self.view addSubview:_titelLabel];
//    [_titelLabel sizeToFit];
    [_titelLabel setTextColor:[UIColor whiteColor]];
    [_titelLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
//    _titelLabel.backgroundColor = [UIColor yellowColor];
    _titelLabel.numberOfLines = 0;
    _titelLabel.textAlignment = 1;


    self.buttonplay = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 65)];
    [bview1 addSubview:_buttonplay];
    [bview1.layer setCornerRadius:43];

    //    buttonplay.backgroundColor = [UIColor orangeColor]
    [_buttonplay setBackgroundImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    [_buttonplay addTarget:self action:@selector(beginAction:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonplay release];

//    buttonplay.backgroundColor = [UIColor orangeColor]
    [_buttonplay setBackgroundImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    [_buttonplay addTarget:self action:@selector(beginAction:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonplay release];

    
    UIButton *buttonstop = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2.27, self.view.frame.size.height / 1.12, 40, 40)];
    [self.view addSubview:buttonstop];
    [buttonstop setBackgroundImage:[UIImage imageNamed:@"iconfont-fangxingtingzhi"] forState:UIControlStateNormal];
    //    buttonstop.backgroundColor = [UIColor magentaColor];
    [buttonstop addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
    [buttonstop release];
    
    self.buttonpause = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 65)];
    [bview2 addSubview:_buttonpause];
    [bview2.layer setCornerRadius:43];
    //    _buttonpause.backgroundColor = [UIColor redColor];
    [_buttonpause addTarget:self action:@selector(pauseAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:bview1];
    [_buttonpause release];
    
    UIButton *buttonnext = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 1.6, self.view.frame.size.height / 1.12, 40, 40)];
    [self.view addSubview:buttonnext];
    //    buttonnext.backgroundColor = [UIColor greenColor];
    [buttonnext setBackgroundImage:[UIImage imageNamed:@"iconfont-ttpodicon-1"] forState:UIControlStateNormal];
    [buttonnext addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [buttonnext release];
    
    UIButton *buttonlast = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4.1, self.view.frame.size.height / 1.12, 40, 40)];
    [self.view addSubview:buttonlast];
    [buttonlast setBackgroundImage:[UIImage imageNamed:@"iconfont-ttpodicon"] forState:UIControlStateNormal];
    //    buttonlast.backgroundColor = [UIColor yellowColor];
    [buttonlast addTarget:self action:@selector(lastAction:) forControlEvents:UIControlEventTouchUpInside];
    [buttonlast release];
    
    
    self.player = [STKAudioPlayer shareSTKAudioPlayer];
    
    
    self.player.delegate = self;
    self.player.volume = 0.6;
    self.player.meteringEnabled = YES;
 
}


- (void)fanhui
{

    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)jilu
{
    JHPlayBackViewController *pbackC = [[JHPlayBackViewController alloc] init];
    [self presentViewController:pbackC animated:YES completion:^{
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)beginAction:(id)sender {
    if (_arr.count == 0) {
         NSURL* url = [NSURL URLWithString:@"http://cdn.y.baidu.com/yinyueren/809189142d9f3f75f57c99ff9beefe3b.mp3"];
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        [self.view bringSubviewToFront:[self.view viewWithTag:2222]];
        [self.roundView startRotation];
        [_buttonpause setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];

    }else{
        
//        NSSet *set = [[NSSet alloc]initWithArray:_arr];
//        [_arr removeAllObjects];
//        for (NSString *str in set) {
//            [_arr addObject:str];
//            if ([_arr containsObject:str]){
//                _selectedIndex = [_arr indexOfObject:str];
//            }else if (![_arr containsObject:str]){
//                [_arr addObject:str];
//                _selectedIndex = [_arr count]-1;
//            }
//            
//        }
    NSURL* url = [NSURL URLWithString:[[_arr lastObject] playPath32]];
     _titelLabel.text = [[_arr lastObject] title];
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    
    [_roundView startRotation];
    [self.view bringSubviewToFront:[self.view viewWithTag:2222]];
    [_buttonpause setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    
    }
}


- (void)nextAction:(UIButton *)btn
{
    _i++;
    NSLog(@"%ld",_arr.count);
    if (_i < _arr.count) {
        NSURL* url = [NSURL URLWithString:[[_arr objectAtIndex:_i] playPath32]];
        _titelLabel.text = [[_arr objectAtIndex:_i] title];
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        
        [_roundView startRotation];
        
        [self.view bringSubviewToFront:[self.view viewWithTag:2222]];
        [_buttonpause setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"亲,已经是最后一首了哦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [self.view addSubview:alertView];
        [alertView show];

    }

   
}

- (void)lastAction:(UIButton *)btn
{
    _i--;
    if (_i > 0) {
        NSURL* url = [NSURL URLWithString:[[_arr objectAtIndex:_i] playPath32]];
        _titelLabel.text = [[_arr objectAtIndex:_i] title];
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        
        [_roundView startRotation];
        
        [self.view bringSubviewToFront:[self.view viewWithTag:2222]];
        [_buttonpause setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"亲,已经是第一首了哦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [self.view addSubview:alertView];
        [alertView show];
        
    }
}

/**
 *  每秒更新slider和label显示时间, timer方法
 */
- (void)track
{
    if (_processSlider) {
        _processSlider.maximumValue = self.player.duration;
        _processSlider.value = self.player.progress;
        
        
        NSInteger proMin = (NSInteger)self.player.progress / 60;
        NSInteger proSec = (NSInteger)self.player.progress % 60;
        
        NSInteger durMin = (NSInteger)self.player.duration / 60;
        NSInteger durSec = (NSInteger)self.player.duration % 60;
        
        _timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    }
}

/**
 *  进度条的方法, 改变播放器的播放进度
 *
 *  @param sender slider参数
 */
- (void)seekSlider:(id)sender {
    
    if (_player) {
        UISlider *processSlider = sender;
        [self.player seekToTime:processSlider.value];
    }
}

// 停止播放
- (void)stopAction:(id)sender {
    [_player stop];
    [_roundView pauseRotation];
    [self.view bringSubviewToFront:[self.view viewWithTag:1111]];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"zhuan" object:@"xiaokang" userInfo:@{@"lol":@"666"}];
    
}

// 暂停按钮
- (void)pauseAction:(id)sender {
    
    NSLog(@"%d", _player.state);
    UIButton *button = sender;
    if (_player.state == STKAudioPlayerStatePaused) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        
        [_player resume];
        [_roundView startRotation];
//        [self.view viewWithTag:1111].alpha = 0.1;
    } else if (_player.state == STKAudioPlayerStatePlaying) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
        [_player pause];
        [_roundView pauseRotation];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"zhuan" object:@"xiaokang" userInfo:@{@"lol":@"666"}];
        
    } else if (_player.state == STKAudioPlayerStateReady) {
        [button setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [_roundView startRotation];
        [self beginAction:nil];
//        [self.view viewWithTag:1111].alpha = 0.1;
    }
}


#pragma mark - 播放器协议方法
/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"播放状态改变");
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(@"结束原因: %d, progress: %f, duration: %f", stopReason, progress, duration);
//    _i++;
//    [self beginAction:self];
//    
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}


@end

